<template>
  <div id="mergerRelationship">
    <Splitpanes horizontal>
      <Pane :size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">合并关系</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading"
              @click="findMergerRelationship"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增"
              @click="handleAdd"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除"
              @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table show-overflow keep-source ref="MergerRelationshipRef" height="auto" align="left"
            :header-cell-style="{ height: '28px', padding: '0px 2px' }" :column-config="{ resizable: true }"
            :loading="loading" :data="MergerRelationshipList"
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }">
            <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
            <vxe-column type="seq" title="序号" width="40"></vxe-column>
            <vxe-column field="rptGroup" title="报告单元"></vxe-column>
            <vxe-column field="mapperItemCode" title="项目代号"></vxe-column>
            <vxe-column field="mapperItemName" title="项目名称"></vxe-column>
            <!-- <vxe-column field="inputCode" title="助记符"></vxe-column> -->
            <!-- <vxe-column title="操作" fixed="right">
              <template #default="{ row }">
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteInstr(row)"
                  class="spanIcon"></vxe-button>
              </template>
            </vxe-column> -->
          </vxe-table>
        </div>

        <el-dialog title="项目" :show-close="false" v-model="showDialog" append-to-body width="1000px"
          :close-on-click-modal="false">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable
                class="vxeInputSearch" placeholder="关键字查询" @clear="getItems" @keyup="keyupInsrEnter"
                @search-click="getItems()"></vxe-input>
              <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="getItems"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="itemTableRef" class="mytable-scrollbar" border="inner" align="left" height="500"
              :data="itemTableList" :loading="lloading" :column-config="{ resizable: true }" resizable show-overflow
              keep-source>
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="rptGroup" title="报告单元"></vxe-column>
              <vxe-column field="itemNo" title="项目代号"></vxe-column>
              <vxe-column field="itemNa" title="项目名称"></vxe-column>
              <vxe-column field="inputCode" title="助记符"></vxe-column>
            </vxe-table>
          </div>
          <div class="dialog-footer flex right justify-end" style="margin-top: 10px;">
            <el-button type="primary" @click="saveBacthItem()">确定</el-button>
            <el-button @click="closeDialog()">取消</el-button>
          </div>
        </el-dialog>

      </Pane>
    </Splitpanes>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';

// 全局变量定义区 ==========
// 获取屏幕高度
let loading = ref(false); //模版加载

let lloading = ref(false); //模版加载

// let itemLoading = ref(false); //项目加载

let showDialog = ref(false);
let searchForm = reactive({
  searchValue: ''
});
let { proxy }: any = getCurrentInstance();
let MergerRelationshipList: any = reactive([]); //模版表格数据
let itemTableList: any = reactive([]); //项目表格数据

// 当前选中项目
let itemDiceInfo: any = reactive({
  id: '',
  instrId: ''
});
// 结果标志 resultflag
let resultflags: any = reactive([]); //字典表：指控规则类型

let iloading = ref(false);
const MergerRelationshipRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记

// 方法定义区 =============

//暴露属性和方法
defineExpose({
  initMergerRelationship
});

// 页面加载时更新列表(左侧)
onMounted(() => {
  getDictDetailList();
});

//从词典获取所有的报告组
// 获取界面字段
function getDictDetailList() {
  iloading.value = true;
  resultflags.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'resultFlag' } })
    .then((res: any) => {
      resultflags.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 接收父组件传值
function initMergerRelationship(row) {
  itemDiceInfo.id = row.id;
  itemDiceInfo.itemNo = row.itemNo;
  itemDiceInfo.itemNa = row.itemNa;
  itemDiceInfo.rptGroup = row.rptGroup;
  if (!IsEmpty(row.rptGroup)) {
    findMergerRelationship();
  }

}

//查询已经关联到的合并关系
function findMergerRelationship() {
  loading.value = true;
  MergerRelationshipList.length = 0;
  const url = '/lab/mapper/item/findMapperItem';
  proxy.$http
    .get(url, { params: { itemNo: itemDiceInfo.itemNo, rptGroup: itemDiceInfo.rptGroup } })
    .then((res: any) => {
      MergerRelationshipList.length = 0;
      MergerRelationshipList.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}

//新增
function handleAdd() {
  getItems();
  showDialog.value = true;
}


// 查询没有关联到本项目的项目
function getItems() {
  lloading.value = true;
  itemTableList.length = 0;
  const url = '/lab/mapper/item/findItemsByRptGroup';
  proxy.$http
    .get(url, { params: { itemNo: itemDiceInfo.itemNo, rptGroupCode: itemDiceInfo.rptGroup, keyWords: searchForm.searchValue } })
    .then((res: any) => {
      itemTableList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('查询仪器列表失败', VxeNotifyType.error);
    });
}


//删除
function handleDelete() {
  const arr = MergerRelationshipRef.value?.getCheckboxRecords(true);
  console.log('arr', arr);

  // const sltTemplates = (proxy.$refs.templateTableRef as any).getCheckboxRecords();
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { labMergerRelationshipList: arr };
        const url = '/lab/mapper/item/batchDeleteMapperItem';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            findMergerRelationship();
            // bacGermFormRef.value?.clearFormData();
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}


// 项目列表隐藏
function closeDialog() {
  searchForm.searchValue = '';
  showDialog.value = false;
}

//绑定关系
function saveBacthItem() {
  const selectRows = (proxy.$refs.itemTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addItemList = [];
    //const row = rptGroupTable.value?.getCurrentRecord();
    for (const sltRow of selectRows) {
      const addInstr = {
        id: sltRow.id,
        itemNo: sltRow.itemNo,
        itemNa: sltRow.itemNa,
        rptGroup: sltRow.rptGroup,
      };
      addItemList.push(addInstr);
    }

    const data = { addItemList: addItemList, sourceItem: itemDiceInfo };
    const url = '/lab/mapper/item/batchMapperItemList';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        //getInstrById(rptGroupInfo); // 获取检验仪器表格数据
        findMergerRelationship();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
  closeDialog();
}

</script>
<style lang="scss" scoped>
#mergerRelationship {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  // 最右侧质控靶值设定表格
  .tableBox {
    height: calc(100% - 45px);
  }
}
</style>
